package com.springtest.reflect;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * project : my-learn
 * <p> cglib的demp </p>
 *
 * @author yisl
 * @date 2022-07-11【星期一】
 **/
public class CglibDemo {
    static class Sister{
        public void sing(){
            System.out.println("Im a shasha, i like sing!");
        }
    }
    static class CglibProxy implements MethodInterceptor{
        private Object target;
        public Object getInstance(Object target){
            this.target = target;
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(target.getClass());
            enhancer.setCallback(this);
            return enhancer.create();
        }
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("jiaqiang123");
            Object result = methodProxy.invokeSuper(o,objects);
            System.out.println("jiaqiang456");
            return result;
        }
    }

    public static void main(String[] args) {
        CglibProxy cglibProxy = new CglibProxy();
        Sister sister = (Sister) cglibProxy.getInstance(new Sister());
        System.out.println("cglib name" + sister.getClass().getName());
        sister.sing();
    }
}
